﻿package com.thorqq.magictimer;

import java.io.File;

import com.baidu.mobstat.StatService;
import com.thorqq.magictimer.R;
import com.thorqq.magictimer.download.DownloadProxy;
import com.thorqq.magictimer.download.DownloadSvcConnListener;
import com.thorqq.magictimer.download.DownloadSvcUpdateListener;
import com.thorqq.magictimer.download.TaskInfo;
import com.thorqq.magictimer.util.Util;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

public class DownloadActivity extends Activity 
    implements DownloadSvcConnListener, DownloadSvcUpdateListener
{
    private ListView mDownloadTaskListView;
    private AdapterDownloadTask mDownloadTaskAdapter;
    private Button mBtnClear;
    private Button mBtnReturn;

    //上下文菜单
    private View mMenuView;
    private TextView mMenuDeleteTask;
    private TextView mMenuDeleteTaskAndFile;
    private TextView mMenuRestart;
    private PopupWindow mMenu;
    private final int mMenuHeight = 200;
    private int mCurrentMenuPos;
    
    private DownloadProxy mProxy;

    @Override
    public void onServiceConnected()
    {
        mDownloadTaskAdapter = new AdapterDownloadTask(DownloadActivity.this, mProxy.getAllTask());
        mDownloadTaskAdapter.setActivity(DownloadActivity.this);
        mDownloadTaskListView.setAdapter(mDownloadTaskAdapter);
        mDownloadTaskAdapter.notifyDataSetChanged();
        
        mProxy.registerUpdateListener(this);
    }


    @Override
    public void onDownloadInfoUpdate()
    {
        if(mDownloadTaskAdapter != null)
        {
            mDownloadTaskAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.download_main);
                
        //启动并绑定service
        DownloadProxy.init(this);
        mProxy = DownloadProxy.getInstance();
        mProxy.registerConnListener(this);
        mProxy.startDownloadSvc();
        
        mDownloadTaskListView = (ListView)findViewById(R.id.listViewDownloadTask);
        mDownloadTaskListView.setEmptyView(findViewById(R.id.tvNoDownloadTask));
        mBtnClear = (Button) findViewById(R.id.btn_download_clear);
        mBtnReturn = (Button) findViewById(R.id.btn_download_return);
       
        //上下文菜单
        mMenuView = getLayoutInflater().inflate(R.layout.menu_download, null, false);
        mMenu = new PopupWindow(mMenuView, 
                LinearLayout.LayoutParams.WRAP_CONTENT, 
                LinearLayout.LayoutParams.WRAP_CONTENT,
                true);
        mMenuDeleteTask        = (TextView) mMenuView.findViewById(R.id.tvDeleteDownloadTask);
        mMenuDeleteTaskAndFile = (TextView) mMenuView.findViewById(R.id.tvDeleteDownloadTaskAndFile);
        mMenuRestart           = (TextView) mMenuView.findViewById(R.id.tvDeleteDownloadRestart);

        //上下文菜单 点击其他地方消失
        mMenuView.setOnTouchListener(new View.OnTouchListener()
        {
            @Override
            public boolean onTouch(View v, MotionEvent event)
            {
                if (mMenu != null && mMenu.isShowing())
                {
                    mMenu.dismiss();
                }
                return false;
            }

        });   
        
        //上下文菜单：删除任务
        mMenuDeleteTask.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                int taskid = ((TaskInfo) mDownloadTaskAdapter.getItem(mCurrentMenuPos)).getTaskid();
                mProxy.delete(taskid);
                mDownloadTaskAdapter.notifyDataSetChanged();
                
                mMenu.dismiss();
                mCurrentMenuPos = -1;
            }
        });
        //上下文菜单：删除任务和文件
        mMenuDeleteTaskAndFile.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                TaskInfo task = (TaskInfo) mDownloadTaskAdapter.getItem(mCurrentMenuPos);
                int taskid = task.getTaskid();
                mProxy.delete(taskid);
                mDownloadTaskAdapter.notifyDataSetChanged();
                
                File file = new File(task.getLocalFile());
                file.delete();
                
                mMenu.dismiss();
                mCurrentMenuPos = -1;
            }
        });
        //上下文菜单：重新下载
        mMenuRestart.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                int taskid = ((TaskInfo) mDownloadTaskAdapter.getItem(mCurrentMenuPos)).getTaskid();
                mProxy.initDownloader(taskid);
                mProxy.restart(taskid);

                mMenu.dismiss();
                mCurrentMenuPos = -1;
            }
        });

        //清空
        mBtnClear.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
                int cnt = mDownloadTaskAdapter.getCount();
                for(int i = 0; i < cnt; i++)
                {
                    TaskInfo task = ((TaskInfo) mDownloadTaskAdapter.getItem(i));
                    if(task.getComplete() >= task.getFileSize())
                    {
                        mProxy.delete(task.getTaskid());
                    }
                }
                mDownloadTaskAdapter.notifyDataSetChanged();
            }
        });
        
        //返回
        mBtnReturn.setOnClickListener(new OnClickListener()
        {
            public void onClick(View v)
            {
                finish();
            }
        });
    } 
    
    @Override
    public void onResume()
    {
        super.onResume();

        /**
         * 此处调用基本统计代码
         */
        StatService.onResume(this);
    }

    @Override
    public void onPause()
    {
        super.onPause();

        /**
         * 此处调用基本统计代码
         */
        StatService.onPause(this);
    }

    @Override
    protected void onDestroy()
    {
        mProxy.stopDownloadSvc();

        super.onDestroy();
    }

    //长按download
    public class DownloadClickListener implements OnClickListener 
    {
        private TaskInfo mTask;
        @SuppressWarnings("unused")
        private Context mContext;

        DownloadClickListener(Context context, TaskInfo task) 
        {
            mContext = context;
            mTask = task;
        }
        
        public void setTag(Object o)
        {
            if(o instanceof TaskInfo)
            {
                mTask = (TaskInfo)o;
            }
        }

        @Override
        public void onClick(View v)
        {
            Util.log("Long Click download task[" + mTask.getTaskid() + "]" + mTask.getLocalFile());
                        
            for(int i = 0; i < mDownloadTaskAdapter.getCount(); i++)
            {
                TaskInfo task = (TaskInfo) mDownloadTaskAdapter.getItem(i);
                if(task.getTaskid() == mTask.getTaskid())
                {
                    mCurrentMenuPos = i;
                                        
                    //anchor Bottom
                    int[] location = new  int[2] ;
                    v.getLocationOnScreen(location);
                    int anchorBottom = location[1] + v.getHeight();
                    //分辨率
                    int displayBottom = getResources().getDisplayMetrics().heightPixels;
                    
                    int offset = anchorBottom + mMenuHeight - displayBottom;
                    if(offset > 0)
                    {
                        mMenu.showAsDropDown(v, 0, -offset);
                    }
                    else
                    {
                        mMenu.showAsDropDown(v);
                    }
                    
                    return;
                }
            }
            
            return;
        }
    }

}
